<div class="container-fluid">
	<h4 class="c-grey-900 mT-10 mB-30" th:text="#{alarm.admin.title}"></h4>
	<div class="masonry-item col-md-12">
		
		<div class="bgc-white bd bdrs-3 p-20 mB-20">
			<table id="alarmTable" class="table table-striped table-bordered"
				cellspacing="0" width="100%">
				<thead>
					<tr>
						<th th:text="#{table.alarm.idAlarm}"></th>
						<th th:text="#{table.alarm.description}"></th>
						<th th:text="#{table.alarm.timeBlock}"></th>
						<th th:text="#{table.alarm.active}"></th>
						<th th:text="#{table.alarm.mails}"></th>
					</tr>
				</thead>
			</table>
		</div>
		
		<div class="bgc-white p-20 bd">
			<h6 class="c-grey-900 mB-20" th:text="#{table.alarm.title}"></h6>
			<div class="mT-30">
				<form id="newAlarmForm" th:object="${alarmForm}" th:action="@{/saveconfalarm}" method="post">
					<input type='hidden' id="mailsConcat" th:field="*{mailsConcat}">
					<div class="form-row">
						<div class="form-group col-md-8">
							<label for="idAlarm" th:text="#{form.alarm.idAlarm}"></label> 
							<input type="text" class="form-control primarykey" id="idAlarm" th:field="*{idAlarm}" readonly>
						</div>
						<div class="form-group col-md-4">
							<label for="active" th:text="#{form.alarm.active}"></label>
							<input type="checkbox" id="active" th:field="*{active}" checked>
						</div>
					</div>
					<div class="form-row">
						<div class="form-group col-md-12">
							<label for="description" th:text="#{form.alarm.description}"></label> 
							<input type="text" class="form-control" id="description" readonly>
						</div>
					</div>
					<div class="form-row">
						<div class="form-group col-md-7">
							<label for="timeBlock" th:text="#{form.alarm.timeBlock}"></label> 
							<input type="number" class="form-control" id="timeBlock" th:field="*{timeBlock}" required>
						</div>
					</div>
					<div class="form-row">
						<div class="form-group col-md-12">
							<label for="mails" th:text="#{form.alarm.mails}"></label>
							<select class="select2 col-md-12" id="mails" th:field="*{mails}" required multiple="multiple"> 
								<option th:each="t: ${mailsAlarm}" th:value="${t.idMail}"
									th:text="${t.emailAddress}">
								</option>
							</select>
						</div>
					</div>
					<button id="alarmBtn" type="submit" class="btn btn-primary" th:utext="#{button.save}"></button>
					<button id="cleanBtn" class="btn btn-primary" onclick="cleanForm('#newAlarmForm');" th:utext="#{button.cleanForm}"></button>
				</form>
			</div>
		</div>
	</div>
</div>

<script th:inline="javascript">
$(document).ready(function() {
	
	$('.select2').select2();
	
	
	var actionDelete = /*[[@{/deletealarm}]]*/;
	var editTemplate = /*[[@{/editalarm}]]*/;
	var addTemplate = /*[[@{/addalarm}]]*/;
	var actionSave = /*[[@{/saveconfalarm}]]*/;
	var actionEmails = /*[[@{/confemails}]]*/;
	var getalarms = /*[[@{/confalarmsdatatable}]]*/;
	var tblAlarm = $('#alarmTable').DataTable({
		dom: 'Bfrtip',
	    select: 'single',
	    responsive: true,
	    altEditor: true,
	    buttons: [{extend: 'selected', text: 'Editar', name: 'editPageForm',
	    	action: function ( e, dt, node, config ) {
				// Para el action 'Editar' obtenemos los valores de la fila seleccioanda
				// directamente y los copiamos al formulario
				for (var o = dt, a = [], e = 0; e < o.context[0].aoColumns.length; e++) a.push({
	                id: o.context[0].aoColumns[e].mData,
	            	title: o.context[0].aoColumns[e].sTitle                
	            });
				var d = dt.rows({
                    selected: !0
                })
                
				var idAlarm = d.data()[0][a[0].id]
				var description = d.data()[0][a[1].id]
				var timeBlock = d.data()[0][a[2].id]
				var activeD = d.data()[0][a[3].id]
				
				$.ajax(actionEmails,{
					data:$.param({'id':idAlarm}),
					type:'GET',
					success: function(data){
						$('#mails').select2().val(data).trigger('change');
					},
					error:function(){
						$('#newAlarmForm').append('<div id="errorModalAlarm" class="alert alert-danger" role="alert"><strong>' + [[#{alarm.admin.error.getMail}]] + '</strong></div>');
					}
				});
                
                $("#idAlarm").val(idAlarm);
                $("#description").val(description);
                $("#timeBlock").val(timeBlock);
				$("#active").prop("checked", activeD);
                
			}
	    }],
	    "iTotalRecords": "totalElements",
        "iTotalDisplayRecords": "numberOfElements",
	    
		"processing": true,
	    "serverSide": true,
		"ajax": {
	        "url": getalarms,
	        "dataSrc" : "data",
	        "data": function (data) {
	        	// Datos a pasar al modal
	            data.formId = "newAlarmForm";
	            data.addTemplate = addTemplate;
	        }
	    },
	    "language": {
	        "url": "js/datatables/i18n/spanish.json",
	        select: {
	            rows: {
	                _: "%d filas seleccionadas",
	                1: "1 fila seleccionada"
	            }
	          }
	        },
		"columns": [
	        { "data": "idAlarm" },
	        { "data": "description"},
	        { "data": "timeBlock" },
	        { "data": "active", 
	          "render": function (data, type, row) {
        		if (data == false) {
					return 'No';
        		} else if (data == true){
					return 'Si';
				} else {
					return '';
				}
	          }
			},
	        { "data": "mails", 
	          "render": function (data, type, row) {	
        		if (data != null && data != '' && data != 'undefined') {
					return 'Si';
        		} else {
					return 'No';
				}
	          }
	        }]
		}).on('crudaction', function(e, accion, idUserValet, data, rowindex){
		    // e          Evento Jquery
		    // accion     [add|edit|delete]
		    // pkid       Primer campo en la data [id]                ... en add,    retorna null
		    // data       Los campos adicionales  [campo_1, campo_n]  ... en delete, retorna null
		    // rowindex   El index de la fila para el dataTable       ... en add,    retorna null
		    
		    $('#altEditor-modal .modal-body .alert').remove();
		    // Se muestra la capa 'cargando...'
		    loading();
		    
		    switch(accion){
		        case 'delete':
		            $.ajax(actionDelete,{
		            	data:$.param({'id':data.idAlarm, 'index':rowindex}),
		                type:'POST',
		                success: function(data){
		                    
		                	// Se oculta la capa 'cargando...'
		                	hide();
		                    
		                    $('#altEditor-modal .modal-body .alert').remove();
		                    $('#altEditor-modal').modal('hide');
		                },
		                error:function(){}
		            });
		            break;
		        default:
		            $('#altEditor-modal .modal-body .alert').remove();
		            $('#altEditor-modal .modal-body').append('<div class="alert alert-danger" role="alert"><strong>' + [[#{alarm.admin.error.NotAuthorized}]] + '</strong></div>');
		            break;
		    }
		});
});	

//Control del botón para guardar un correo
$( "#alarmBtn" ).click(function( event ) {
	  event.preventDefault();
	  
	  var tblAlarm = $('#alarmTable').DataTable();
	  var numMails =  $("#mails").select2('data').length;
	  var newMails = "";

	  for (var i=0; i<numMails; i++){
		  newMails += $("#mails").select2('data')[i].id;
	    if (i!=numMails-1){
	    	newMails += "&";
	    }
	  }
	
	  $("#newAlarmForm input")[0].value = newMails;
	  
	  var formData = JSON.stringify($("#newAlarmForm").serializeJSON());
	  var url = /*[[@{/saveconfalarm}]]*/;
	  
	  loading();
	  if ($('#newAlarmForm')[0].checkValidity() === false) {
		  hide();
		  
		  $('#newAlarmForm *').filter(':input').each(function(){
      	    
	          if(!$(this)[0].checkValidity()){
	      	   	$("#" + $(this).attr('id')).addClass("has-error");
	      	  } else {
	      	   	$("#" + $(this).attr('id')).removeClass("has-error");
	      	  }
      	    
      	  });
		  
		  if ($("#mails").select2('data').length == 0){
			  $('#errorModalAlarm2').remove();
			  $('#newAlarmForm').append('<div id="errorModalAlarm2" class="alert alert-danger" role="alert"><strong>' + [[#{alarm.admin.error.oneMail}]] + '</strong></div>');
		  }else{
			  $('#errorModalAlarm2').remove();
		  }
		  
	  } else{
		  $.ajax({
			  type: "POST",
			  url: url,
			  data: formData,
			  success: function(data, error){
				  var errores = JSON.parse(data.error);
				  
				  if (data.error != null){
					  jQuery.each(errores, function(i, val) {
					  	$('#newAlarmForm *').filter('span').each(function(){
							if (i == $(this).attr('id')){
								$("#" + i).text(val);
							}
						});
					  });
				  }else{
					  $("#newAlarmForm")[0].reset();
					  
					  $('#newAlarmForm *').filter('span').each(function(){
							$(this).text('');
						});
					$("#newAlarmForm select").select2().val('').change();
				  }
				  
				  hide();
				  tblAlarm.row.add($(data.data)).draw(false);
				  
				  $('#newAlarmForm *').filter(':input').each(function(){
					 $("#" + $(this).attr('id')).removeClass("has-error");
				  });
				   
				  if ($('#errorModalAlarm').length > 0){
					 $('#errorModalAlarm').remove();
				  }
				  if ($('#errorModalAlarm2').length > 0){
					 $('#errorModalAlarm2').remove();
				  }
				  
			  },
			  error:function(){
				  hide();
				  if ($('#errorModalAlarm').length > 0){
						 $('#errorModalAlarm').remove();
					  }
				  $('#newAlarmForm').append('<div id="errorModalAlarm" class="alert alert-danger" role="alert"><strong>' + [[#{alarm.admin.error.sameName}]] + '</strong></div>');
			  },
			  dataType: "json",
			  contentType : "application/json"
			});
	  }
  
});

function cleanForm(f){
	
	$(f + ' *').filter(':input').each(function(){
		$(this).val('');
	});
	
	$(f + ' *').filter('span').each(function(){
		$(this).text('');
	});
	
	$(f + " select").select2().val('').change();
	
	$(f).find(".alert").remove();

}

</script>